package com.zhenwei.zscm.service;

import com.zhenwei.zscm.common.base.RestMsg;
import com.zhenwei.zscm.common.base.RestResult;
import com.zhenwei.zscm.model.vo.productPart.ProductPartVO;
import com.zhenwei.zscm.repo.LogRepo;
import com.zhenwei.zscm.repo.ProductPartRepo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class ProductPartService {
    private ProductPartRepo repo;
    private LogRepo logRepo;
    private final String LOG_TYPE = "产品配件管理";

    public RestResult getList(String productCode){
        var list = repo.getProductPartByProductCode(productCode);
        return RestResult.success(list, list.size());
    }

    public RestResult create(ProductPartVO vo) {
        // 检查产品是否添加过配件
        boolean exists = repo.checkProductPartExists(vo.getProductCode(),vo.getPartName());
        if(exists) {
            return RestResult.fail(RestMsg.PRODUCT_PART_EXISTS);
        }
        boolean b = repo.create(vo);
        if(b) {
            logRepo.createAsync(LOG_TYPE, "添加产品配件->"+vo);
        }
        return RestResult.r(b);
    }

    public RestResult update(ProductPartVO vo) {
        // 检查产品是否添加过配件
        boolean exists = repo.checkProductPartExists(vo);
        if(exists) {
            return RestResult.fail(RestMsg.PRODUCT_PART_EXISTS);
        }
        var updated = repo.update(vo);
        if(updated){
            logRepo.createAsync(LOG_TYPE, "修改产品配件->"+vo);
        }
        return RestResult.r(updated);
    }

    public RestResult delete(String guid) {
        boolean deleted = repo.delete(guid);
        if(deleted) {
            logRepo.createAsync(LOG_TYPE, "删除产品配件->"+guid);
        }
        return RestResult.r(deleted);
    }
}
